<script setup lang="ts">
import type { getManageRegionsListApi } from '@/apis/modules/regions'
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import {
  addManageRegionApi,
  updateManageRegionByIdApi,
} from '@/apis/modules/regions'
import { E_SWITCH_STATUS } from '@/enums/common'
import { flagUrl, getCodesOptions } from '@/utils/country'
import { Message } from '@arco-design/web-vue'

interface IEmit {
  (e: 'update:visible', visible: boolean): void
  (e: 'refresh'): void
}

interface IProps {
  record: ApiListItem<typeof getManageRegionsListApi>
}

const props = defineProps<IProps>()

const emit = defineEmits<IEmit>()

const visible = defineModel<boolean>({ required: true })

const loading = ref(false)
const formRef = ref<FormInstance>()
const formData = reactive({
  id: '',
  name: '',
  name_en: '',
  region_url: '',
  region: '',
  user_name: '',
  password: '',
  remark: '',
  country: '',
  status: E_SWITCH_STATUS.ENABLE,
})
const formRules: Record<string, FieldRule[]> = {
  name: [{ required: true, message: '请输入区域名称' }],
  name_en: [{ required: true, message: '请输入区域英文名' }],
  country: [{ required: true, message: '请选择' }],
  region_url: [{ required: true, message: '请输入区域地址' }],
  region: [{ required: true, message: '请输入Region' }],
  user_name: [{ required: true, message: '请输入用户名' }],
  password: [{ required: true, message: '请输入密码' }],
}

const codeOptions = getCodesOptions()

// 表单提交
async function handleSubmit() {
  const res = await formRef.value?.validate()
  if (res) {
    return false
  }
  try {
    loading.value = true
    const name = JSON.stringify({
      'zh-CN': formData.name,
      'en': formData.name_en,
    })
    if (props.record) {
      await updateManageRegionByIdApi({ ...formData, name })
    } else {
      await addManageRegionApi({ ...formData, name })
    }
    emit('refresh')
    Message.success(props.record ? '更新成功' : '创建成功')
    // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (error) {
    loading.value = false
    return false
  }
}

watchPostEffect(() => {
  if (!visible.value) {
    loading.value = false
    formRef.value?.resetFields()
    return
  }
  if (props.record) {
    const name = JSON.parse(props.record.name!)
    formData.id = String(props.record.id!)
    formData.name = name['zh-CN']!
    formData.name_en = name.en
    formData.country = props.record.country!
    formData.region_url = props.record.region_url!
    formData.region = props.record.region!
    formData.user_name = props.record.user_name!
    formData.password = props.record.password!
    formData.remark = props.record.remark!
    formData.status = Number(props.record.status!)
  }
})
</script>

<template>
  <a-drawer
    v-model:visible="visible"
    :title="record ? '编辑区域' : '新建区域'"
    width="480px"
    :mask-closable="false"
    ok-text="保存"
    :on-before-ok="handleSubmit"
    :ok-loading="loading"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item
        label="区域名称"
        field="name"
        required
        hide-asterisk
        asterisk-position="end"
      >
        <a-input
          v-model="formData.name"
          placeholder="请输入区域名称"
          show-word-limit
          :max-length="20"
        />
      </a-form-item>
      <a-form-item
        label="英文名"
        field="name_en"
        required
        hide-asterisk
        asterisk-position="end"
      >
        <a-input
          v-model="formData.name_en"
          placeholder="请输入区域英文名"
          show-word-limit
          :max-length="40"
        />
      </a-form-item>
      <a-form-item
        label="所属国家"
        field="country"
        required
        hide-asterisk
        asterisk-position="end"
      >
        <a-select
          v-model="formData.country"
          :options="codeOptions"
          placeholder="请选择"
        >
          <template #label="{ data }">
            <span class="flex items-center gap-x-2">
              <img
                v-if="data?.value"
                class="aspect-[4/3] h-15px rounded-sm"
                :src="flagUrl(String(data?.value ?? ''))"
                :alt="data?.label"
              >
              <span class="text-xs"> {{ data?.label }}</span>
            </span>
          </template>
        </a-select>
      </a-form-item>
      <a-form-item
        label="区域地址"
        field="region_url"
        required
        hide-asterisk
        asterisk-position="end"
      >
        <a-input
          v-model="formData.region_url"
          placeholder="请输入区域地址"
          show-word-limit
          :max-length="256"
        />
      </a-form-item>
      <a-form-item
        label="Region"
        field="region"
        required
        hide-asterisk
        asterisk-position="end"
      >
        <a-input
          v-model="formData.region"
          placeholder="请输入Region"
          show-word-limit
          :max-length="30"
        />
      </a-form-item>
      <a-form-item
        label="用户名"
        field="user_name"
        required
        hide-asterisk
        asterisk-position="end"
      >
        <a-input
          v-model="formData.user_name"
          placeholder="请输入用户名"
          show-word-limit
          :max-length="30"
        />
      </a-form-item>
      <a-form-item
        label="密码"
        field="password"
        required
        hide-asterisk
        asterisk-position="end"
      >
        <a-input-password
          v-model="formData.password"
          placeholder="请输入密码"
          :max-length="64"
        />
      </a-form-item>
      <a-form-item
        label="备注"
        field="remark"
      >
        <a-input
          v-model="formData.remark"
          placeholder="请输入备注"
          show-word-limit
          :max-length="20"
        />
      </a-form-item>
      <a-form-item
        field="status"
        label="状态"
        required
        hide-asterisk
        asterisk-position="end"
      >
        <a-radio-group
          v-model="formData.status"
          :options="[
            { label: '启用', value: E_SWITCH_STATUS.ENABLE },
            { label: '禁用', value: E_SWITCH_STATUS.DISABLE },
          ]"
        />
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<style scoped lang="scss"></style>
